package com.ruoyi.api.controller;

import java.util.List;
import java.util.Random;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.domain.model.WebLoginBody;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.SendMessage;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.system.domain.DzCode;
import com.ruoyi.system.domain.SysNotice;
import com.ruoyi.system.service.IDzCodeService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysNoticeService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.token.TokenService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.DzHuiyuan;
import com.ruoyi.system.service.IDzHuiyuanService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 用户信息Controller
 * 
 * @author ruoyi
 * @date 2022-09-01
 */
@RestController
@RequestMapping("/api/huiyuan")
public class DzHuiyuanApiController extends BaseController
{
    @Autowired
    private IDzHuiyuanService dzHuiyuanService;

    @Autowired
    private IDzCodeService dzCodeService;


    @Autowired
    private ISysNoticeService noticeService;

    @Autowired
    private ISysDeptService deptService;

    @GetMapping("/noticelist")
    public TableDataInfo list(SysNotice notice)
    {
        startPage();
        List<SysNotice> list = noticeService.selectNoticeList(notice);
        return getDataTable(list);
    }

    @GetMapping("/deptlist")
    public TableDataInfo deptlist(SysDept dept)
    {
        List<SysDept> list = deptService.selectDeptWebList(dept);
        return getDataTable(list);
    }

    @PostMapping("/noticeinfo")
    public AjaxResult getinfo(SysNotice notice)
    {
        SysNotice notice1 = noticeService.selectNoticeById(notice.getNoticeId());
        return AjaxResult.success(notice1);
    }

    @GetMapping(value = "/dept/{deptId}")
    public AjaxResult getDeptInfo(@PathVariable Long deptId)
    {
        return AjaxResult.success(deptService.selectDeptById(deptId));
    }

    @PostMapping("/login")
    public AjaxResult login(@RequestBody WebLoginBody loginBody)
    {
        AjaxResult ajax = AjaxResult.success();
        String loginpass = SecurityUtils.encryptPassword(loginBody.getPassword());

        DzHuiyuan dzHuiyuan = new DzHuiyuan();
        dzHuiyuan.setLoginname(loginBody.getLoginname());
        List<DzHuiyuan> list = dzHuiyuanService.selectDzHuiyuanWebList(dzHuiyuan);
        if(list!=null&&list.size()>0){
            DzHuiyuan dzHuiyuan2 = list.get(0);
            if(SecurityUtils.matchesPassword(loginpass,dzHuiyuan2.getPassword())){

                return AjaxResult.error(-2,"账号密码错误");
            }else{
                return AjaxResult.error(-2,"账号密码错误");
            }
        }else{
            return  AjaxResult.error(-1,"账号不存在，请先注册账号");
        }

//        // 生成令牌
//        String token = dzHuiyuanService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
//                loginBody.getUuid());
//        ajax.put(Constants.TOKEN, token);
//        return ajax;
    }

    @PostMapping("/sms")
    public AjaxResult sms(@RequestBody DzHuiyuan dzHuiyuan)
    {

        try {
            int max=10000;
            int min=1000;
            Random random = new Random();
            String code =  (random.nextInt(max - min) + min + 1)+"";
            dzHuiyuan.setCode(code);
            System.out.println("向手机"+dzHuiyuan.getDn()+"发送验证码："+code);
            DzCode dzCode = new DzCode();
            dzCode.setCode(dzHuiyuan.getCode());
            dzCode.setDn(dzHuiyuan.getDn());
            dzCode.setIsused(0l);
            dzCodeService.insertDzCode(dzCode);
            SendSmsResponse response = SendMessage.sendSms(dzHuiyuan.getDn(), dzHuiyuan.getCode());
            if(response.getCode()=="OK"){

                return  AjaxResult.success();
            }else{
                return  AjaxResult.success();
            }

        } catch (ClientException e) {
            return  AjaxResult.success();
        }
    }


    @PostMapping("/updatepass")
    public AjaxResult updatepass(@RequestBody DzHuiyuan dzHuiyuan)
    {
        DzCode dzCode = new DzCode();
        dzCode.setCode(dzHuiyuan.getCode());
        dzCode.setDn(dzHuiyuan.getDn());
        dzCode.setIsused(0l);
        List<DzCode> codeList = dzCodeService.selectDzCodeListWeb(dzCode);
        if(codeList!=null&&codeList.size()>0){
            DzCode dzCodeobj = codeList.get(0);
            dzCodeobj.setIsused(1l);
            dzCodeService.updateDzCode(dzCodeobj);
            if(dzHuiyuan.getPassword()!=null&&!dzHuiyuan.getPassword().trim().equals("")){
                dzHuiyuan.setPassword(SecurityUtils.encryptPassword(dzHuiyuan.getPassword()));
            }
            return toAjax(dzHuiyuanService.updateDzHuiyuan(dzHuiyuan));

        }else{
            return  AjaxResult.error(-1,"验证码错误");
        }

    }

    /**
     * 查询用户信息列表
     */
    @GetMapping("/list")
    public TableDataInfo list(DzHuiyuan dzHuiyuan)
    {
        startPage();
        List<DzHuiyuan> list = dzHuiyuanService.selectDzHuiyuanWebList(dzHuiyuan);
        return getDataTable(list);
    }

    /**
     * 导出用户信息列表
     */
    @Log(title = "用户信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DzHuiyuan dzHuiyuan)
    {
        List<DzHuiyuan> list = dzHuiyuanService.selectDzHuiyuanList(dzHuiyuan);
        ExcelUtil<DzHuiyuan> util = new ExcelUtil<DzHuiyuan>(DzHuiyuan.class);
        util.exportExcel(response, list, "用户信息数据");
    }

    /**
     * 获取用户信息详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(dzHuiyuanService.selectDzHuiyuanById(id));
    }

    /**
     * 新增用户信息
     */
    @Log(title = "用户信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody DzHuiyuan dzHuiyuan)
    {


        DzCode dzCode = new DzCode();
        dzCode.setCode(dzHuiyuan.getCode());
        dzCode.setDn(dzHuiyuan.getDn());
        dzCode.setIsused(0l);
        List<DzCode> codeList = dzCodeService.selectDzCodeListWeb(dzCode);
        if(codeList!=null&&codeList.size()>0){
            DzCode dzCodeobj = codeList.get(0);
            dzCodeobj.setIsused(1l);
            dzCodeService.updateDzCode(dzCodeobj);
            DzHuiyuan temp = new DzHuiyuan();
            temp.setLoginname(dzHuiyuan.getLoginname());
            List<DzHuiyuan> list = dzHuiyuanService.selectDzHuiyuanWebList(temp);
            if(list!=null&&list.size()>0){
                return AjaxResult.error(-1,"账号已存在");
            }else{
                dzHuiyuan.setPassword(SecurityUtils.encryptPassword(dzHuiyuan.getPassword()));
                return toAjax(dzHuiyuanService.insertDzHuiyuan(dzHuiyuan));
            }

        }else{
            return  AjaxResult.error(-1,"验证码错误");
        }




    }

    /**
     * 通用上传请求（单个）
     */
    @PostMapping("/upload")
    public AjaxResult uploadFile(MultipartFile file) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);

            HttpServletRequest request = ServletUtils.getRequest();
            StringBuffer url = request.getRequestURL();
            String contextPath = request.getServletContext().getContextPath();
            String url1= url.delete(url.length() - request.getRequestURI().length(), url.length()).append(contextPath).toString();


            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url1);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }


    /**
     * 修改用户信息
     */
    @Log(title = "用户信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DzHuiyuan dzHuiyuan)
    {
        return toAjax(dzHuiyuanService.updateDzHuiyuan(dzHuiyuan));
    }

    /**
     * 删除用户信息
     */
    @Log(title = "用户信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(dzHuiyuanService.deleteDzHuiyuanByIds(ids));
    }
}
